package com.hmp.recruit.sys.user.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.hmp.recruit.common.utils.DBUtils;
import com.hmp.recruit.sys.user.vo.SysUser;

public class UserDao {
	private QueryRunner runner = null;// 查询运行器

	public UserDao() {
		runner = new QueryRunner();
	}

	// 方法：向数据库中添加一条记录
	public void add(SysUser u) {
		String sql = "insert into t_sys_user(account, password, nickname) values(?, ?, ?)";
		try {
			runner.update(DBUtils.getConnection(), sql, u.getAccount(), u.getPassword(), u.getNickname());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	// 方法：根据id向数据库中修改某条记录
	public void update(SysUser u) {
		String sql = "update t_sys_user set account = ?, password = ?, nickname = ? where id = ?";
		try {
			runner.update(DBUtils.getConnection(), sql, u.getAccount(), u.getPassword(), u.getNickname(), u.getId());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	// 方法：根据id删除数据库中的某条记录
	public void delete(int id) {
		String sql = "delete from t_sys_user where id=?";
		try {
			runner.update(DBUtils.getConnection(), sql, id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	// 方法：使用BeanHandler查询一个对象
	public SysUser findById(int id) {
		String sql = "select account, password, nickname from t_sys_user where id=?";
		SysUser p = null;
		try {
			p = runner.query(DBUtils.getConnection(), sql, new BeanHandler<SysUser>(SysUser.class), id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return p;
	}

	// 方法：使用BeanListHandler查询所有对象
	public List<SysUser> findAll() {
		String sql = "select account, password, nickname from t_sys_user";
		List<SysUser> sysUsers = null;
		try {
			sysUsers = runner.query(DBUtils.getConnection(), sql,
					new BeanListHandler<SysUser>(SysUser.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return sysUsers;
	}

	// 方法：使用ScalarHandler查询一共有几条记录
	public long sysUserCount() {
		String sql = "select count(*) from t_sys_user";
		try {
			return runner.query(DBUtils.getConnection(), sql, new ScalarHandler<Long>());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public SysUser login(String account, String password) {
		String sql = "select account, password, nickname from t_sys_user where account = ? and password = ?";
		SysUser p = null;
		try {
			p = runner.query(DBUtils.getConnection(), sql, new BeanHandler<SysUser>(SysUser.class), account, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return p;
	}
}
